package com.photoeditor.demo.util;

import android.content.Context;
import android.support.constraint.ConstraintLayout;
import android.text.TextPaint;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.base.utils.DeviceUtils;

public class measureTextViewSizeUtils {

    public static void measureTextViewSize(Context context,TextView textView,int maxTextWidth) {
        if(textView==null){
            return;
        }
        int measuredWidth = DeviceUtils.dip2px(maxTextWidth);
        if (canShowSpecifiesLengthText(textView,measuredWidth)) {
            float textSize = textView.getTextSize();
            final float valueSp2 = DeviceUtils.sp2pxF(1);
            TextPaint textPaint = textView.getPaint();
            String text = textView.getText().toString();
            int textViewWidth = (int) textPaint.measureText(text);
            do {
                textSize=textSize-valueSp2;
                textPaint.setTextSize(textSize);
                textViewWidth = (int) textPaint.measureText(text);

            } while (textViewWidth > measuredWidth);
            textView.setTextSize(DisplayUtils.pxtosp(context,textSize));
        }
    }

    private static boolean canShowSpecifiesLengthText(TextView textView,int maxTextWidth) {
        if (maxTextWidth == 0) {
            return false;
        }
        TextPaint textPaint = textView.getPaint();
        String text = textView.getText().toString();
        int textViewWidth = (int) textPaint.measureText(text);
        if (textViewWidth<=maxTextWidth) {
            return false;
        }
        return true;
    }

    public static void measureTextView(Context context,TextView textView,int maxTextWidth,int marginTop) {
        if(textView==null){
            return;
        }
        int measuredWidth = DeviceUtils.dip2px(maxTextWidth);
        if (canShowSpecifiesLengthText(textView,measuredWidth)) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
            layoutParams.topMargin = DeviceUtils.dip2px(marginTop);
            layoutParams.width=measuredWidth;
            textView.setLayoutParams(layoutParams);
            textView.setSingleLine(false);
            textView.setMaxLines(2);
        }
    }


}
